package com.waitingsnow.common.share
{
import com.waitingsnow.common.share.tweetr.Tweetr;
import com.waitingsnow.common.share.tweetr.oauth.OAuth;
import com.waitingsnow.common.share.tweetr.oauth.events.OAuthEvent;
import com.waitingsnow.common.share.qqMicroBlog.operation.IRequestOperation;
import com.waitingsnow.common.share.config.AppInfo;
import com.waitingsnow.common.share.util.DataUtils;
import com.waitingsnow.core.debug.Logger;

import flash.events.Event;
import flash.events.LocationChangeEvent;
import flash.media.StageWebView;
import flash.net.SharedObject;
import flash.net.URLVariables;
import flash.utils.ByteArray;

import mx.logging.ILogger;

/**
 * twitter分享
 * @author NeilWang
 *
 */
public class ShareToTwitter extends BaseShare
{
    //==========================================================================
    //  Class variables
    //==========================================================================
    
    //==========================================================================
    //  Constructor
    //==========================================================================
    /**
     * Constructs a new <code>ShareToTwitter</code> instance.
     *
     */
    public function ShareToTwitter()
    {
        super();
        addEventListener(Event.ADDED_TO_STAGE, init);
        init();
    }
    //==========================================================================
    //  Properties
    //==========================================================================
    private var access_token:String;
    
    private var request:IRequestOperation;
    
    private var authorize:OAuth;
    
    private var tempOauthToken:String;
    
    private var twitter:Tweetr;
    
    private var so:SharedObject;
    
    //==========================================================================
    //  Methods
    //==========================================================================
    /**
     * 初始化 
     * @param parames
     * 
     */    
    private function init(...parames):void
    {
        checkToken();
    }
    
    /**
     * 先从缓存中获取应用ID和应用密钥
     */		
    override public function checkToken():void
    {
        so = SharedObject.getLocal("shareKit/Twitter");
        access_token = so.data.access_token;
        //判断是否已经授权
        if(access_token)
        {
            authorize = new OAuth();
            authorize.consumerKey = AppInfo.TWITTER_APP_KEY;
            authorize.consumerSecret = AppInfo.TWITTER_APP_SECRET;
            authorize.oauthToken = so.data.access_token;
            authorize.oauthTokenSecret = so.data.token_secret;
            //已经被授权，直接获取数据
			Logger.debug("已经被授权，直接获取数据");
            initTwitter();
        }
        else
        {
            //开始获取授权
            startAuth();
        }
    }   
    
    /**
     * 初始化twitter 
     * 
     */    
    private function initTwitter():void
    {
        twitter = new Tweetr();
        twitter.oAuth = authorize;
    }
    
    /**
     * 授权
     * 
     */    
    private function startAuth():void
    {
        authorize = new OAuth();
        authorize.consumerKey = AppInfo.TWITTER_APP_KEY;
        authorize.consumerSecret = AppInfo.TWITTER_APP_SECRET;
        authorize.callbackURL = AppInfo.CALL_BACK;
        authorize.addEventListener(OAuthEvent.CALL_AUTHORIZE, callAuthorizeHandler);
        authorize.addEventListener(OAuthEvent.COMPLETE, oauthCompleteHandler);
        authorize.getAuthorizationRequest();
    }
    
    /**
     * 获取accessToken 
     * 
     */    
    private function getAccessToken(url:String):void
    {
        var authorURL:String = url;
        webView = new StageWebView();
        webView.stage = stage;
        webView.viewPort = area;
        webView.loadURL(encodeURI(authorURL));
        webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING,
            webViewChangeHandler);
        webView.addEventListener(Event.COMPLETE, webViewCompleteHandler);
        webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, 
            webViewChangeHandler);
    }
    
    /**
     * 分享 
     * @param message
     * @param picUrl
     * 
     */    
    override public function share(message:String = "", pic:ByteArray = null):void
    {
        twitter.updateStatueWithMedia(message, pic);
    }
    
    /**
     * 从地址上获取verifier（授权码） 
     * @param url
     * 
     */    
    private function checkBackUrl(url:String):void
    {
		Logger.debug(url);
        var urlVar:URLVariables = DataUtils.getURLVariables(url);
        var verifier:String = urlVar.oauth_verifier;
        if (verifier)
        {
            authorize.requestAccessToken(verifier);
            webView.dispose();
            webView = null;
        }
    }
    
    //==========================================================================
    //  Event Handlers
    //==========================================================================
    /**
     * 登录成功 
     * @param event
     * 
     */    
    private function oauthCompleteHandler(event:OAuthEvent):void
    {
		Logger.debug("登录授权成功");
        so.data["access_token"] = authorize.oauthToken;
        so.data["token_secret"] = authorize.oauthTokenSecret;
        so.flush();
        initTwitter();
    }
    
    private function callAuthorizeHandler(event:OAuthEvent):void
    {
        getAccessToken(event.url);
    }
    
    private function webViewChangeHandler(event:LocationChangeEvent):void
    {
        checkBackUrl(webView.location);
    }
    
    private function webViewCompleteHandler(event:Event):void
    {
        checkBackUrl(webView.location);
    }
}
}